import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_09_game/config/app_color.dart';
import 'package:flutter_09_game/config/app_config.dart';
import 'package:flutter_09_game/config/history_route_ovserver.dart';
import 'package:flutter_09_game/generated/assets.dart';
import 'package:flutter_09_game/generated/locales.g.dart';
import 'package:flutter_09_game/http/http_export.dart';
import 'package:flutter_09_game/pages/main/model_app_package.dart';
import 'package:flutter_09_game/utils/loading/loading_utils.dart';
import 'package:flutter_09_game/utils/log/utils_log.dart';
import 'package:flutter_09_game/widgets/dialog/notice_popup_dialog.dart';
import 'package:flutter_09_game/widgets/dialog/widget_dialog_package.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:url_launcher/url_launcher_string.dart';

class UtilsOther {
  static List<String> recordTeamOptions = [
    LocaleKeys.funds.tr,
    LocaleKeys.hash.tr,
    LocaleKeys.game.tr,
    LocaleKeys.team.tr,
  ];

  String getAmountTagIcon(String? tag) {
    return tag?.toUpperCase() == "TRX"
        ? Assets.commonTrxTag
        : Assets.commonUsdtTag;
  }

  String? getAmountTagNullIcon(String? tag) {
    return tag?.toUpperCase() == "TRX"
        ? Assets.commonTrxTag
        : tag?.toUpperCase() == "USDT"
            ? Assets.commonUsdtTag
            : null;
  }

  /// 格式化投注地址
  static String formatWithdrawAddress(String? address) {
    if (address == null || address.isEmpty) {
      return LocaleKeys.notBound.tr;
    }
    if (address.length <= 8) {
      return address;
    }
    return '${address.substring(0, 4)}****${address.substring(address.length - 4)}';
  }

  static copyMemberId(String memberId) {
    if (memberId == '--') return;
    clog('dakjsdhkhj   $memberId');
    Clipboard.setData(ClipboardData(text: memberId));
    LoadingUtils.showToast(LocaleKeys.copySuccess.tr);
  }

  /// 获取区块哈希的最后6位
  static String getLastSixDigits(String? blockHash, {int count = 8}) {
    if (blockHash == null || blockHash.isEmpty) {
      return count == 6 ? '...000000' : '...00000000';
    }
    if (blockHash.length >= count) {
      return '...${blockHash.substring(blockHash.length - count)}';
    }

    return '...$blockHash';
  }

  static openVerify(var round) {
    if (round != null) {
      launchUrlString('${AppConfig.verifyUrl}$round',
          mode: LaunchMode.externalApplication);
    }
  }

  static int getGameDuration(int? type) {
    switch (type) {
      case 1: // 3秒
        return 3;
      case 2: // 1分钟
        return 60;
      case 3: // 3分钟
        return 180;
      case 4: // 6秒
        return 6;
      case 5: // 9秒
        return 9;
      case 6: // 9秒
        return 15;
      case 7: // 9秒
        return 30;
      default:
        return 60;
    }
  }

  static Color getResultColor(int? result) {
    if (result == null) return AppColor.textPrimary.withOpacity(0.7);
    return (result % 2 == 1)
        ? AppColor.homePrizePoolIndicator
        : AppColor.gameResultEven;
  }

  static Widget buildHashDigitsViewString(
    String blockHash,
    int? result, {
    int count = 8,
    Color? textColor,
    Color? hashColor,
  }) {
    String hash = UtilsOther.getLastSixDigits(blockHash, count: count);
    String resultStr = result.toString();
    int lastIndex = hash.lastIndexOf(resultStr);
    List<String> hashs;
    if (lastIndex != -1) {
      hashs = [
        hash.substring(0, lastIndex),
        hash.substring(lastIndex, lastIndex + resultStr.length),
        hash.substring(lastIndex + resultStr.length),
      ];
    } else {
      hashs = [hash, ''];
    }
    return Text.rich(
      TextSpan(
        style: TextStyle(
          fontSize: 12.sp,
          fontWeight: FontWeight.w400,
          color: textColor ?? AppColor.textPrimary.withOpacity(0.7),
        ),
        children: [
          TextSpan(
            text: hashs.first,
          ),
          TextSpan(
            text: '${result ?? ''}',
            style: TextStyle(
              color: hashColor ?? getResultColor(result),
            ),
          ),
          TextSpan(
            text: hashs.last,
          ),
        ],
      ),
    );
  }

  getAppPackage({bool isLoading = false}) async {
    HttpResponse response = await HttpManager().get(API.getAppPackage,
        params: {'version': "V${AppConfig.version}"},
        fromJson: ModelAppPackage.fromJson,
        uiType: isLoading ? HttpUIType.loadingAndToast : HttpUIType.none);
    if (response.isSuccess) {
      ModelAppPackage appPackage = response.data;
      // appPackage.version = '0.1.0';
      if (isVersionGreater(appPackage.version ?? '', AppConfig.version)) {
        routeHistoryObserver.removeName(NoticePopupDialog.name);
        WidgetDialogPackage.show(appPackage: response.data);
      } else {
        if (isLoading) {
          LoadingUtils.showToast(LocaleKeys.latestVersion.tr);
        }
      }
    }
  }

  bool isVersionGreater(String v1, String v2) {
    // 去掉前缀 "v"
    v1 = v1.replaceAll(RegExp(r'^[vV]'), '');
    v2 = v2.replaceAll(RegExp(r'^[vV]'), '');

    // 拆分成 [主版本, 次版本, 修订号]
    final parts1 = v1.split('.').map(int.parse).toList();
    final parts2 = v2.split('.').map(int.parse).toList();

    // 不足三位的补 0，例如 1.2 => 1.2.0
    while (parts1.length < 3) parts1.add(0);
    while (parts2.length < 3) parts2.add(0);

    for (int i = 0; i < 3; i++) {
      if (parts1[i] > parts2[i]) return true;
      if (parts1[i] < parts2[i]) return false;
    }

    return false; // 完全相等则返回 false（不大于）
  }
}
